package com.cyx.netty.c1;

import java.nio.ByteBuffer;

public class TestByteBufferExam {
    public static void main(String[] args) {
        /*
        黏包半包解析
         */
        ByteBuffer source = ByteBuffer.allocate(32);
        source.put("Hello, world\nI'm Amy\nHo".getBytes());
        split(source);
        source.put("w are you\n".getBytes());
        split(source);
    }

    public static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            // 找到一条完整消息
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                // 把这条完整消息存入新的ByteBuffer
                ByteBuffer target = ByteBuffer.allocate(length);
                // 从buffer读，向target写
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                out(target);
            }
        }
        source.compact();
    }

    public static void out(ByteBuffer buffer) {
        buffer.flip();
        while (buffer.hasRemaining()) {
            byte b = buffer.get();
            System.out.print(((char) b));
        }
    }
}
